package com.situ.yB2C.util;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.net.util.Base64;
//import org.apache.commons.net.util.Base64;
/**
 * .可逆的加密
 * 
 * @author wxinpeng
 *
 */
public class DESUtil {
	private static final String DES = "DES";

	/**
	 * 公钥 8位以上
	 */
	private static final String SECRET_KEY = "12345678";

	/**
	 * . 获取秘钥对象
	 * 
	 * @return
	 */
	private static final SecretKey getSecretKeyFactory() {
		SecretKey secretKey = null;
		try {
			SecretKeyFactory desFactory = SecretKeyFactory.getInstance(DES);
			secretKey = desFactory.generateSecret(new DESKeySpec(SECRET_KEY.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException | InvalidKeySpecException e) {
			e.printStackTrace();
		}
		return secretKey;
	}

	/**
	 * 加密
	 * 
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static final String encryption(String param) {
		try {
			Cipher cipher = Cipher.getInstance(DES);
			SecretKey secretKey = getSecretKeyFactory();
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			return new String(Base64.encodeBase64(cipher.doFinal(param.toString().getBytes())));
		} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException | BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param value
	 * @return
	 * @throws Exception
	 */
	public static final String decrypt(String value) {
		try {
			Cipher cipher = Cipher.getInstance(DES);
			SecretKey secretKey = getSecretKeyFactory();
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			return new String(cipher.doFinal(Base64.decodeBase64(value.getBytes())));
			//return new String(cipher.doFinal(Base64.decodeBase64(value.getBytes())));
		} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException | BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

}
